#!/bin/bash

# 设置颜色
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

echo -e "${GREEN}Starting development environment setup...${NC}"

# 检查必要工具
echo -e "${YELLOW}Checking required tools...${NC}"
command -v node >/dev/null 2>&1 || { echo -e >&2 "${RED}Node.js is required but not installed. Aborting.${NC}"; exit 1; }
command -v npm >/dev/null 2>&1 || { echo -e >&2 "${RED}npm is required but not installed. Aborting.${NC}"; exit 1; }
command -v docker >/dev/null 2>&1 || { echo -e >&2 "${RED}Docker is required but not installed. Aborting.${NC}"; exit 1; }

# 创建必要的目录
echo -e "${YELLOW}Creating required directories...${NC}"
mkdir -p logs
mkdir -p uploads
mkdir -p nginx/ssl

# 安装依赖
echo -e "${YELLOW}Installing dependencies...${NC}"
npm install

# 创建环境文件
echo -e "${YELLOW}Setting up environment files...${NC}"
if [ ! -f .env ]; then
    cp .env.example .env
    echo -e "${GREEN}Created .env file from template${NC}"
fi

# 生成SSL自签名证书(用于开发)
echo -e "${YELLOW}Generating self-signed SSL certificate for development...${NC}"
if [ ! -f nginx/ssl/cert.pem ] || [ ! -f nginx/ssl/key.pem ]; then
    openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
        -keyout nginx/ssl/key.pem -out nginx/ssl/cert.pem \
        -subj "/C=CN/ST=Shanghai/L=Shanghai/O=Development/CN=localhost"
    echo -e "${GREEN}Generated self-signed SSL certificate${NC}"
fi

# 启动开发环境容器
echo -e "${YELLOW}Starting development containers...${NC}"
docker-compose up -d

# 等待数据库准备就绪
echo -e "${YELLOW}Waiting for database to be ready...${NC}"
sleep 5

# 初始化数据库
echo -e "${YELLOW}Initializing database...${NC}"
npm run db:migrate
npm run db:seed

echo -e "${GREEN}Development environment setup complete!${NC}"
echo -e "${YELLOW}You can now run 'npm run dev' to start the development server${NC}"
